package com.ckm;

import com.ckm.creator.DefaultMongoSourceCreator;
import com.ckm.provider.DBMongoSourceProvider;
import com.ckm.provider.DynamicMongoSourceProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootApplication
public class MongoTestApplication {

	public static void main(String[] args) {
		SpringApplication.run(MongoTestApplication.class, args);
	}

	@Bean
	public DynamicMongoSourceProvider dbMongoSourceProvider(DefaultMongoSourceCreator defaultMongoSourceCreator){
		String uri = "mongodb://localhost:27017/123";
		String collectionName="hello";

		return new DBMongoSourceProvider(defaultMongoSourceCreator,uri,collectionName) {
			@Override
			protected Map<String, MongoProperties> getMongoSource(String uri, String collectionName) {
				MongoTemplate mongoTemplate = new MongoTemplate(new SimpleMongoClientDatabaseFactory(uri));
				List<Map> all = mongoTemplate.findAll(Map.class, collectionName);
				HashMap<String, MongoProperties> mapList = new HashMap<>();
				for (Map map : all) {
					MongoProperties mongoProperties = new MongoProperties();
					mongoProperties.setUri((String) map.get("uri"));
					mapList.put(String.valueOf(map.get("key")),mongoProperties);
				}
				return mapList;
			}
		};
	}

}
